package com.ljc.app.demo.puzzle;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import java.util.List;

public class PuzzleView extends RelativeLayout {


    //默认3*3
    private int mColumn = 3;
    //容器的内边距
    private int mPadding = 0;
    //小图的距离 dp
    private int mMargin = 1;
    //图片
    private Bitmap mBitmap;
    //切图后存储
    private List<ImagePiece> mItemBitmaps;
    //标记
    private boolean once;

    //容器的一个宽度
    private int mWidth;
    private int mHeight;
    private ImageView[] mPuzzleItems;


    public PuzzleView(Context context) {

        this(context, null);
    }

    public PuzzleView(Context context, AttributeSet attrs) {

        this(context, attrs, 0);
    }

    public PuzzleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context, attrs);
    }

    /**
     * 初始化
     */
    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PuzzleView);
        mColumn = typedArray.getInteger(R.styleable.PuzzleView_column, 3);
        float border = typedArray.getDimension(R.styleable.PuzzleView_border, 1);
        int imageId = typedArray.getResourceId(R.styleable.PuzzleView_image, 0);
        typedArray.recycle();
        initBitmap(imageId);
        mMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, border, getResources().getDisplayMetrics());

        mPadding = min(getPaddingLeft(), getPaddingRight(), getPaddingTop(), getPaddingBottom());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //拿到容器的高宽最小值
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();

        if (!once) {
            initItem();
            once = true;
        }
        setMeasuredDimension(mWidth, mHeight);
    }

    /**
     * 进行切图和排序
     */
    private void initBitmap(int imageId) {
        //判断是否存在这张图片
        if (imageId == 0) {
            mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.default_img);
        }
        else {
            mBitmap = BitmapFactory.decodeResource(getResources(), imageId);
        }
        //进行裁剪
        mItemBitmaps = ImageSplitterUtil.splitImage(mBitmap, mColumn);
    }

    /**
     * 设置imageview(item)的宽高等属性
     */
    private void initItem() {
        //（ 容器的宽度 - 内边距 * 2  - 间距  ） /  裁剪的数量
        int mItemWidth = (mWidth - mPadding * 2 - mMargin * (mColumn - 1)) / mColumn;
        int mItemHeight = (mHeight - mPadding * 2 - mMargin * (mColumn - 1)) / mColumn;

        //mColumn * mColumn
        mPuzzleItems = new ImageView[mColumn * mColumn];

        //开始排放
        for (int i = 0; i < mPuzzleItems.length; i++) {
            ImageView item = new ImageView(getContext());
            //设置图片
            item.setImageBitmap(mItemBitmaps.get(i).getBitmap());
            item.setScaleType(ImageView.ScaleType.CENTER_CROP);
            //保存
            mPuzzleItems[i] = item;
            //设置ID
            item.setId(i + 1);
            //设置Tag
            item.setTag(i + "_" + mItemBitmaps.get(i).getIndex());

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(mItemWidth, mItemHeight);

            //判断不是最后一列
            if (i + 1 % mColumn != 0) {
                lp.rightMargin = mMargin;
            }

            //判断不是第一列
            if (i % mColumn != 0) {
                lp.addRule(RelativeLayout.RIGHT_OF, mPuzzleItems[i - 1].getId());
            }

            //判断如果不是第一行
            if ((i + 1) > mColumn) {
                lp.topMargin = mMargin;
                lp.addRule(RelativeLayout.BELOW, mPuzzleItems[i - mColumn].getId());
            }
            addView(item, lp);
        }
    }

    /**
     * 获取多个参数的最小值
     */
    private int min(int... params) {
        int min = params[0];
        //遍历
        for (int param : params) {
            if (param < min) {
                min = param;
            }
        }
        return min;
    }

    public ImageView[] getPuzzleItems() {
        return mPuzzleItems;
    }


}